import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/cookies' // get token from cookie
import i18n from '@/lang'
import defaultSettings from '@/settings'
import { getMenuLangList } from '@/api/system/menu'

const getPageTitle = (key) => {
  const hasKey = i18n.te(`route.${key}`)
  if (hasKey) {
    const pageName = i18n.t(`route.${key}`)
    return `${pageName} - ${defaultSettings.title}`
  }
  return `${defaultSettings.title}`
}

NProgress.configure({ showSpinner: false }) // NProgress Configuration
const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      if (store.getters.hasInfo) {
        next()
      } else {
        try {
          const menuList = await getMenuLangList()
          const menuLang = { zh: { route: {}}, ja: { route: {}}, en: { route: {}}}
          menuList.data.listLine.forEach((item) => {
            menuLang.zh.route[item.routeName] = item.displayNameZh
            menuLang.ja.route[item.routeName] = item.displayNameJa ? item.displayNameJa : item.displayNameZh
            menuLang.en.route[item.routeName] = item.displayNameEn ? item.displayNameEn : item.displayNameZh
          })
          i18n.mergeLocaleMessage('en', menuLang.en)
          i18n.mergeLocaleMessage('zh', menuLang.zh)
          i18n.mergeLocaleMessage('ja', menuLang.ja)

          await store.dispatch('user/getInfo')
          const accessRoutes = await store.dispatch('perm/generateRoutes',
            { isAdmin: store.getters.isAdmin, roles: store.getters.roles })
          for (const route of accessRoutes) {
            router.addRoute(route)
          }
          router.addRoute({ path: '*', redirect: '/404', hidden: true })
          await store.dispatch('user/redirect', accessRoutes)

          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({ ...to, replace: true })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach((to) => {
  // finish progress bar
  NProgress.done()
  // set page title
  document.title = getPageTitle(to.meta.title)
})
